//Requires prototype, proto.menu, 

document.observe('dom:loaded', initMemonaut);
window.onbeforeunload = function(){
     return "You might have unsaved changes! Press Cancel to go back and save your changes."; // "Do you want to leave without saving your changes?";
 }

var gxCurrentScrap = null;
var gxClipboard = null;
var gbAddMode = "eCurrentScrapAfter";
var gbInfoDisplay = true;

var gbNumbering = false;
var gbHideIcons = false;
var gbShowInfo  = false;

var gsDocTitle="";
var gsDocFilename="";
var gxDragger=null;

if(!gasNotebooks)
    var gasNotebooks = [];
    
function initMemonaut() {
    Model_init();
    View_init();
    Controller_init();
    StatusBar_clear(); //For OK, startup prompt
}

function about() 
{
    alert('Memonaut Mind-Mapper\nVersion 0.60 (C) 2010 The Oraclique \nDeveloped by SonOfDelphi\nhttp://memonaut.googlecode.com/');
}

function Controls_show()
{
    $$('#Scrapbook .clicker').each(function (elmt)	{
                    elmt.show();
            });

    $$('#Scrapbook .foldindicator').each(function (elmt)	{
                    elmt.show();
            });
   gbHideIcons = false;
}

function Controls_hide()
{
    $$('#Scrapbook .clicker').each(function (elmt){
                    elmt.hide();});
    $$('#Scrapbook .foldindicator').each(function (elmt){
                    elmt.hide(); });
    gbHideIcons = true;
}

function InfoDisplay_hide()
{
	$$('#Scrapbook .info').each(function (elmt){elmt.hide()});
        gbInfoDisplay = false;
}

function InfoDisplay_show()
{
    $$('#Scrapbook .info').each(function (elmt){elmt.show()});
    gbInfoDisplay = true;
    displayStatus('Info shown for all notes.');
}

function Numbering_on()
{
    $$('#paneScrapbook ol').each(function (elmt){elmt.addClassName('numbering')});
    gbNumbering = true;
}

function Numbering_off()
{
    $$('#paneScrapbook ol').each(function (elmt){elmt.removeClassName('numbering')});
    gbNumbering = false;
}

function Scrap_activateWrapper(wrapper, edit)
{
    var target= wrapper.down('.scrap');
    target.immediateDescendants().each(function (elmt)
            {
                if(elmt.hasClassName('content')) {
                    var x = new Proto.EIP( {type: 'textarea', item: elmt, cols:40} );
                    if(edit)
                            x.edit();
                    elmt.observe('click', ScrapContent_onClick);

                    if(Prototype.Browser.Opera)
                        elmt.observe('mouseup', Content_onDrop);
                    else
                        elmt.observe('mouseover', Content_onDrop);
                }
            });

   var iconScrap = viewCreateScrap();
   var iconControls = viewCreateControls();

   target.insert({before:iconScrap});
   target.insert({before:iconControls});

    //TODO Doing brute-force for 0.40. Need to fine-tune
    if(gbHideIcons) Controls_hide();
    if(!gbInfoDisplay) InfoDisplay_hide();
    if(gbNumbering) Numbering_on();
}

function viewCreateScrap()
{
    var button = document.createElement('img');
    button.setAttribute('src',gsAppDir + 'note.png');
    button.setAttribute('class','clicker');
    button.addClassName('view');

    button.setAttribute('title','Click to select.Double-click to fold/expand.\nRight-click for menu.Drag and drop enabled.');
    button.observe('dblclick',ScrapIcon_onDoubleClick);
    button.observe('mousedown', ScrapIcon_onMouseDown);
    button.observe('mouseup', ScrapIcon_onMouseUp);

    if(Prototype.Browser.Opera)
        button.observe('mouseup', ScrapIcon_onDrop);
    else
        button.observe('mouseover', ScrapIcon_onDrop);

    return button;
}

function viewCreateControls()
{
    var button = document.createElement('img');
    button.setAttribute('src',gsAppDir + 'down.png');
    button.setAttribute('title','Click for menu');
    button.addClassName('iconActions');
    button.addClassName('view');
    button.addClassName('controls')
    button.setAttribute('src',gsAppDir + 'down.png');

    return button;
}

function ScrapIcon_onDoubleClick(ev){
	var target = ev.target.up('.wrapper').down('.scrap');
	Scrap_toggleFold(target);
        CurrentScrap_setNew(target);
	ev.stop();
}

function FoldIndicator_onClick(ev){
	var target = ev.target.up(0).down('.scrap');
	Scrap_toggleFold(target);
        CurrentScrap_setNew(target);
}

function Scrap_toggleFold(elmt)
{
	var target = elmt;
	
	if(!target.down('.commentlist'))
		return;
		
	if(!target.hasClassName('minimized')){
                activateMinimized(target);
                displayStatus('Folded note.');

	}
	else {
		target.removeClassName('minimized');
                if(target.previous('.foldindicator'))
                    target.previous('.foldindicator').remove();
		target.immediateDescendants().each(function (elmt) 
			{
				if(elmt.hasClassName('commentlist')){
						elmt.show();
				}
			});
                displayStatus('Expanded note.');
	}

}

function ScrapContent_onClick(ev){
	var target = ev.target.up('.wrapper').down('.scrap');
	CurrentScrap_setNew(target);
}

function Scrap_createWithWrapper(text)
{
	var wrapper = document.createElement('li');
	wrapper.addClassName('wrapper');
	
	var scrap = document.createElement('span');
	scrap.addClassName('scrap');

	var info   = document.createElement('span');
	info.addClassName('info');

	var currentTime = new Date();
	var month = currentTime.getMonth() + 1;month= month>9? month:'0'+month;
	var day = currentTime.getDate();day= day>9? day:'0'+day;
	var year = currentTime.getFullYear();
	var hours = currentTime.getHours(); hours= hours>9? hours:'0'+hours;
	var minutes = currentTime.getMinutes();minutes= minutes>9? minutes:'0'+minutes;
	var seconds = currentTime.getSeconds();seconds= seconds>9? seconds:'0'+seconds;

	var infoText = 'Added at ' + hours + ':' + minutes + ':' + seconds+ ' on '+  year + '-' + month + '-' + day  ;
	info.insert({top:document.createElement('br')});
	info.insert({bottom:infoText});
	
	var content = document.createElement('span');
	content.addClassName('content');
	content.insert(text);
	
	scrap.insert({bottom:content});
	scrap.insert({bottom:info});
	
	wrapper.insert({bottom:scrap});
	return wrapper;
}

function getAddLocation()
{
    var location = $('Scrapbook');

    if(gbAddMode == "eCurrentScrapAfter")
        location = gxCurrentScrap ? gxCurrentScrap.up('.wrapper'): location;
    else if(gbAddMode == "eCurrentScrapInto"){
        if(gxCurrentScrap){
            location = Scrap_getCommentList(gxCurrentScrap.up('.wrapper'));
        }
    }
    return location;
}

function addScrap(idSourceInput)
{
	var text= $F($(idSourceInput));
	text = text.replace(/&/g, "&amp;").replace(/</g,"&lt;").replace(/>/g, "&gt;");
	//doesn't work :( text.replace(/\n/g,"<br>");

	if(text.blank()){
		$(idSourceInput).value="Enter some text to add!";
		$(idSourceInput).removeClassName('editing');
		return;
	}
	
	var wrapper=Scrap_createWithWrapper(text);
	var addToLocation = getAddLocation();
        var scrollToLocation = wrapper;
        
        switch(gbAddMode)
        {
           case "eScrapbookTop":
                addToLocation.insert({top:wrapper});
                break;
                
            case "eCurrentScrapAfter":
                 if(gxCurrentScrap) addToLocation.insert({after:wrapper});
                 else addToLocation.insert({top:wrapper});
               break;

            case "eCurrentScrapInto":
                 if(gxCurrentScrap) {
                     addToLocation.insert({bottom:wrapper});
                 }
                 else addToLocation.insert({top:wrapper});
               break;

            case "eScrapbookLast":
                 addToLocation.insert({bottom:wrapper});
               break;
        }

    Scrap_activateWrapper(wrapper);
    gxMenuScrap.refresh();
    gxMenuClip.refresh();

    intelliScroll(scrollToLocation);
    if(gbAddMode != "eCurrentScrapInto")
        CurrentScrap_setNew(wrapper.down('.content'));


    displayStatus('Added note.');
}

function saveFile(bNoPrompt)
{
    if(!isSaveAllowed()){
       return;
    }

    if($('DocFilename').options.is_empty){
         displayStatus("Please enter a filename.");
         $('DocFilename').innerHTML = getCurrentFilename();
         $('DocFilename').edit();
        return;
    }

    var saveFilename = $('DocFilename').innerHTML;
    removeUIForSave(); //TODO: Better is to filter the view elements out

    if(!isNewFilename(getCurrentFilename(), saveFilename)){
         saveNotebookList();
         displayStatus(saveCurrentFile());
         restoreUI();
         return;
    }

    if(!bNoPrompt)
        if(!confirm("Save to file " + saveFilename + "?")){
            displayStatus("File not saved.");
            restoreUI(); //TODO: Above 
            return;
        }

    if(saveFilename.lastIndexOf(".html") <= 0)
        saveFilename = saveFilename +".html";

    displayStatus(saveFileAs(saveFilename));

    restoreUI();//TODO: Above 
}

function textareaScrap_onClick (element)
{
	if(!element.hasClassName('editing'))
	{
		element.select();
		element.addClassName('editing');
		element.value = '';
	}
}

function Scrap_info(elmt)
{
    var target = elmt.up('.wrapper').down('.scrap');
    target = target.down('.info');
    if(target.visible())
            target.hide();
    else
            target.show();
}

function toggleScrapInfo(evt)
{
    Scrap_info(evt.target);
}

function Bookmark_activate(elmt)
{
	var target = elmt;
	
	new Proto.EIP( {
		type: 'text',
		item: target,
		save_url: 'edit.php',
		is_wrapped:true
	} );
	
	target.observe('click', Bookmark_scrollTo);
}

function Scrap_bookmark(elmt)
{
	var target = elmt.up('.wrapper').down('.scrap');
	target = target.down('.content');

	var location = target.identify();
	var addToLocation=$('listBookmarks');

	var bookmark = document.createElement('a');
	bookmark.addClassName('bookmark');
	
	var item = document.createElement('li');
	
	var button = document.createElement('img');
	button.setAttribute('src', gsAppDir + 'bookmark.png');
	button.setAttribute('class', 'iconBookmark');
	button.setAttribute('title', 'Click for menu.');

	bookmark.setAttribute('href', "#"+ target.id);
	var text = Prototype.Browser.IE? target.innerText:target.textContent;
	text = (text.length > 20)? text.substring(0,19): text;
	bookmark.insert(text);
	item.insert({top:bookmark});
	item.insert({top:button});
	addToLocation.insert({top:item});
	
	Bookmark_activate(bookmark);
        gxMenuBookmarks.refresh();
    
}

function addBookmark(evt)
{
    Scrap_bookmark(evt.target);
}

function Bookmark_scrollTo(evt)
{
	var target = evt.target;

	var location = target.readAttribute('href');
	location=$(location.replace(/#/,''));
	if(location)
		CurrentScrap_setNew(location);
}

function CurrentScrap_getNew(scrapElement)
{
    var cursor = scrapElement.up('.wrapper');
    var check = null;

    check = cursor.next('.wrapper');
    if(check){
        return check.down('.scrap');
    }
    
    check = cursor.previous('.wrapper')
    if(check) {
        return check.down('.scrap');
    }
    
    check = cursor.up('.wrapper');
    if(check){
        return check.down('.scrap');
    }

    return null;
}

function deleteScrap(evt){
    Scrap_delete(evt.target);
}

function Scrap_delete(elmt)
{
	var target =  elmt.up('.wrapper');

	var currentCheck = target.down('.scrap');
	if(currentCheck){
		if(currentCheck.hasClassName('current')){
 			var result = CurrentScrap_getNew(gxCurrentScrap);
                        if(result)
                            CurrentScrap_setNew(result);
                        else
                            gxCurrentScrap = null;
                }
                        
	}

	target.remove();
        displayStatus('Deleted note.');
}

function Scrap_move(elmt, moveUp)
{
	var swapitem = elmt.up('.wrapper');
	var swappers = moveUp ? swapitem.previousSiblings(): swapitem.nextSiblings();
	
	if (swappers.length > 0){
		var swapper = swappers[0];
		Scrap_swap(swapitem, swapper);
                displayStatus('Shifted note.');
	}
        else displayStatus('Cannot move further.');
}

function Scrap_swap(swapitem, swapper)
{
        // Inner HTML copy won't do..0.30 bug
        var temp = swapper.cloneNode(false); // no need to clone deep
        Element.replace(swapitem, temp);
        Element.replace(swapper, swapitem);
        Element.replace(temp, swapper); // make sure references (like event observers) are kept
}


function shiftUpScrap(evt)
{
	var elmt = evt.target;
	Scrap_move(elmt, true);
}

function shiftDownScrap(evt)
{
	var elmt = evt.target;
	Scrap_move(elmt, false);
}

function Scrap_shiftOut(elmt)
{
    var target = elmt.up('.wrapper');
    var check = target.up('.wrapper');
    if(!check){
            displayStatus('Already at top level.');
            return;
    }

    check.insert({after:target});

    gxMenuScrap.refresh();
    gxMenuClip.refresh();

    displayStatus('Shifted note.');
}

function shiftOutScrap(evt)
{
	var target = evt.target;
        Scrap_shiftOut(target);
}

function Scrap_shiftIntoPrevious(elmt)
{
    var target = elmt.up('.wrapper');
    var check = target.previous('.wrapper');
    if(!check){
            displayStatus('No previous note to move into.');
            return;
    }

    check = Scrap_getCommentList(check);
    check.insert({bottom:target});

    gxMenuScrap.refresh();
    gxMenuClip.refresh();

    displayStatus('Shifted note.');
}

function shiftIntoPreviousScrap(evt)
{
    var target = evt.target;
    Scrap_shiftIntoPrevious(target);
}

function Scrap_shiftIntoNext(elmt)
{
    var target = elmt.up('.wrapper');
    var check = target.next('.wrapper');
    if(!check){
            displayStatus('No next note to move into.');
            return;
    }
    check = Scrap_getCommentList(check);
    check.insert({top:target});

    gxMenuScrap.refresh();
    gxMenuClip.refresh();

    displayStatus('Shifted note.');
}

function shiftIntoNextScrap(evt)
{
	var target = evt.target;
        Scrap_shiftIntoNext(target);
}

function dummy()
{
	alert("Not implemented yet!");
}

function addNote(evt)
{
    Scrap_addNote(evt.target, false);
}

function Scrap_addNote(elmt, bAsNext)
{
	var target = elmt.up('.wrapper'); // .down('.scrap');
	
	var note = Scrap_createWithWrapper('');
	if(!bAsNext){
            var commentList = Scrap_getCommentList(target);
            commentList.insert({bottom:note});
        }
        else{
            target.insert({after:note});
            CurrentScrap_setNew(note.down('.scrap'), false)
        }
        
        note.show();
        intelliScroll(target);

	Scrap_activateWrapper(note, true);
	gxMenuScrap.refresh();
        gxMenuClip.refresh();

        displayStatus('Adding note.');
}

function Scrap_getCommentList(elmt)
{
	var target = elmt;
	target = target.down('.scrap');
	
	var commentList =  target.down('ol');
	if(!commentList){
		commentList = document.createElement('ol');
		commentList.addClassName('commentlist');
		target.insert({bottom:commentList});
	}
	
	if(!commentList.visible())
		Scrap_toggleFold(target);
	
	return commentList;
}

function setCurrentScrap(ev)
{
	var target = ev.target.up('.wrapper').down('.scrap');
	CurrentScrap_setNew(target);
}

function CurrentScrap_reset()
{
	if(!gxCurrentScrap)
		return;
	gxCurrentScrap.removeClassName('current');
	gxCurrentScrap = null;
}

function CurrentScrap_setNew(element, bScrollTo)
{
	CurrentScrap_reset();
		
	element.addClassName('current');
	gxCurrentScrap = element;

        if(bScrollTo){
            var father = gxCurrentScrap.up('.wrapper').up('.wrapper')
            if(father) intelliScroll(father); else intelliScroll(gxCurrentScrap);
        }
}

function removeUIForSave()
{
    $$('.protomenu').each(function (elmt)	{
                    elmt.remove();
            });

    $$('.view').each(function(elmt){
        elmt.remove();
    });

    NotebookList_clear();
}

function restoreUI()
{
    initDocumentElements();
    initMenuMemonaut();
}

function checkForEdits()
{
    var isEditInProgress = $$('.eip_editing');
    if(isEditInProgress.length > 0)
        return true;
    return false;
}
function changeAddMode(elmt)
{
    gbAddMode = elmt.options[elmt.selectedIndex].value;
}

function Bookmark_delete(evt)
{
	var target = evt.target;
	target = target.up(0);
	target.remove();
}

function Bookmark_move(elmt, moveUp)
{
	var swapitem = elmt;
	var swappers = moveUp ? swapitem.previousSiblings(): swapitem.nextSiblings();
	
	if (swappers.length > 0){
		var swapper = swappers[0];
		Bookmark_swap(swapitem, swapper);
	}
}

function Bookmark_swap(swapitem, swapper)
{
	if( (swapitem.down('.eip_editing')) || (swapper.down('.eip_editing'))){
		displayStatus("Please complete your edit before moving.");
		return;
	}

	//This is OK only because there are no child elements. Otherwise handlers lost...
        var itemtext = swapper.innerHTML;
	swapper.innerHTML = swapitem.innerHTML;
	swapitem.innerHTML = itemtext;

	Bookmark_activate(swapitem.down('.bookmark'));
	Bookmark_activate(swapper.down('.bookmark'));

	gxMenuBookmarks.refresh();
}

function Bookmark_rename(evt)
{
	var target = evt.target.up(0).down('.bookmark');
        target.edit();

}

function Bookmark_moveUp(evt)
{
	var elmt = evt.target.up(0);
	Bookmark_move(elmt, true);
}

function Bookmark_moveDown(evt)
{
	var elmt = evt.target.up(0);
	Bookmark_move(elmt, false);
}

function ScrapEntry_handlerKeypress(evt)
{
    if(evt.keyCode == Event.KEY_RETURN){
        addScrap($('textareaScrap'));
        evt.stop();
        $('textareaScrap').value="";
    }
}

function AddNote_onClick(elmt)
{
    addScrap('textareaScrap');
    $('textareaScrap').value="What's on your mind?";
    $('textareaScrap').removeClassName('editing');
}

function CurrentScrap_addNote()
{
    if(!gxCurrentScrap) return;
    Scrap_addNote(gxCurrentScrap,false);
}

function CurrentScrap_addNext(){
    if(!gxCurrentScrap) return;
    Scrap_addNote(gxCurrentScrap,true);
}

function CurrentScrap_delete(){
    if(!gxCurrentScrap) return;
    Scrap_delete(gxCurrentScrap);
}

function CurrentScrap_moveUp(){
    if(!gxCurrentScrap) return;
    var check = gxCurrentScrap.up('.wrapper').previous('.wrapper');
    check? CurrentScrap_setNew(check.down('.scrap'),true): displayStatus("Cannot move up further at this level");
}

function CurrentScrap_moveDown(){
    if(!gxCurrentScrap) return;
    var check = gxCurrentScrap.up('.wrapper').next('.wrapper');
    check? CurrentScrap_setNew(check.down('.scrap'),true): displayStatus("Cannot move down further at this level");
 }

function CurrentScrap_moveIn(){
    if(!gxCurrentScrap) return;
    var check = gxCurrentScrap.down('.commentlist');
    if (check){
        if(!check.visible()) check.show();
        check = check.down('.wrapper');
        check ? CurrentScrap_setNew(check.down('.scrap'),true): displayStatus("Comment-list empty.");
    }
    else
        displayStatus('Already at innermost note.');
}

function CurrentScrap_moveOut(){
    if(!gxCurrentScrap) return;
    var check = gxCurrentScrap.up('.commentlist');
    if (check){
        check = check.up('.wrapper');
        check? CurrentScrap_setNew(check.down('.scrap'), true): displayStatus("Comment-list empty.");
    }
    else
        displayStatus('Already at top level.');
}

function CurrentScrap_shiftUp(){
    if(!gxCurrentScrap) return;
    Scrap_move(gxCurrentScrap, true);
}

function CurrentScrap_shiftDown(){
   if(!gxCurrentScrap) return;
   Scrap_move(gxCurrentScrap, false);
}

function CurrentScrap_shiftIntoPrevious(){
    if(!gxCurrentScrap) return;
    Scrap_shiftIntoPrevious(gxCurrentScrap);
}

function CurrentScrap_shiftIntoNext(){
    if(!gxCurrentScrap) return;
    Scrap_shiftIntoNext(gxCurrentScrap);
}

function CurrentScrap_shiftOut(){
    if(!gxCurrentScrap) return;
    Scrap_shiftOut(gxCurrentScrap);
}

function Scrap_edit(elmt){
    var target = elmt.up('.wrapper').down('.scrap').down('.content');
    target.edit();
    displayStatus('Editing note.');
}

function CurrentScrap_edit(){
    if(!gxCurrentScrap) return;
    Scrap_edit(gxCurrentScrap);
}

function editScrap(evt){
    Scrap_edit(evt.target);
}

function CurrentScrap_info(){
    if(!gxCurrentScrap) return;
    Scrap_info(gxCurrentScrap);
}

function CurrentScrap_bookmark(){
    if(!gxCurrentScrap) return;
    Scrap_bookmark(gxCurrentScrap);
}

function Scrap_copy(elmt)
{
    dummy();
}

function CurrentScrap_copy(){
    if(!gxCurrentScrap) return;
    Scrap_cut(gxCurrentScrap);
}

function CurrentScrap_cut(){
    if(!gxCurrentScrap) return;
    Scrap_cut(gxCurrentScrap);
}

function CurrentScrap_paste(){
    if(!gxCurrentScrap) return;
    Scrap_paste(gxCurrentScrap);
}

function copyScrap(evt){
    Scrap_copy(evt.target);
}

function Scrap_cut(elmt)
{
    if(gxClipboard){
        if(!gxClipboard.visible())
            Scrap_delete(gxClipboard.down('.scrap'));
    }
    
    var target = elmt.up('.wrapper');
    var currentCheck = target.down('.scrap');
    
    if(currentCheck){
            if(currentCheck.hasClassName('current')){
                    var result = CurrentScrap_getNew(gxCurrentScrap);
                    if(result)
                        CurrentScrap_setNew(result);
                    else
                        CurrentScrap_reset();
            }

    }
    gxClipboard = target;
    gxClipboard.hide();
    displayStatus('Content moved to clipboard.');
}

function cutScrap(evt)
{
    Scrap_cut(evt.target);
}

function Scrap_paste(elmt)
{
    if(!gxClipboard)
        return;
    var target = elmt.up('.wrapper');
    var check = Scrap_getCommentList(target);
    check.insert({top:gxClipboard});
    if(!gxClipboard.visible()) gxClipboard.show();
    gxClipboard = null;
    displayStatus('Pasted note.');
}

function pasteScrap(evt)
{
    Scrap_paste(evt.target);
}

function cancelClipboard(evt)
{
    if(!gxClipboard)
        return;

    if(!gxClipboard.visible())
        gxClipboard.show();
    
    gxClipboard = null;
    displayStatus('Restored note.');
}

function StatusBar_show(msg)
{
    $('Status').innerHTML =  '<center>' + msg + '</center>';
    setTimeout ( "StatusBar_clear()", 3500 );
}

function StatusBar_clear()
{
    $('Status').innerHTML = 'OK.';
}

function displayStatus(msg)
{
    StatusBar_show(msg);
}

function ScrapIcon_onMouseDown(evt)
{
    var target = evt.target.up('.wrapper');
    gxDragger = target;
    target = target.down('.content');
    CurrentScrap_setNew(target);
}

function Content_onDrop(evt)
{
    var source = gxDragger;
    gxDragger = null;
    if(!source) return;

    var target = evt.target.up('.wrapper');
    if(!target)
        return;
    if(source == target)
        return;
    if(target.descendantOf(source)){
        displayStatus('Cannot move into own subsection.');
        return;
    }
    if(target.previous(0)==source)
        target.insert({after:source});
    else
        target.insert({before:source});

    displayStatus('Moved note.');
}

function ScrapIcon_onDrop(evt)
{
    var source = gxDragger;
    gxDragger = null;
    if(!source) return;

    var target = evt.target.up('.wrapper');
    if(!target)
        return;
    if(source == target)
        return;
    if(target.descendantOf(source)){
        displayStatus('Cannot move into own subsection.');
        return;
    }

    var check = Scrap_getCommentList(target);
    check.insert({top:source});

    displayStatus('Inserted note.');
}

function ScrapIcon_onMouseUp(evt)
{
    gxDragger = null;
}

function Notepod_setFocus(evt)
{
    $('textareaScrap').focus();
}

function titleChange(newTitle)
{
    document.title = newTitle;
}

function isNewFilename(oldname, newname)
{
    //Removes the extension .html
    var extensionPos = newname.lastIndexOf(".html");
    if(extensionPos > 0){
        newname = newname.substring(0, extensionPos).toLowerCase();
    }

    extensionPos = oldname.lastIndexOf(".html");
    if(extensionPos > 0){
        oldname = oldname.substring(0, extensionPos).toLowerCase();
    }

    if(oldname == newname)
        return false;
    return true;
}
function fileChange(newname, oldname)
{
    if(!isNewFilename(oldname, newname))
        return oldname + '.html';

    if(newname.lastIndexOf(".html") <0)
        newname = newname + '.html';
    
    if(confirm("Save this file as "+ newname + " now?")){
            if(!isSaveAllowed())
                return newname + '.html';
            
            saveFile(true);
        }
    return newname;
}

function removeExtension(filename)
{
        var extensionPos = filename.lastIndexOf(".html");
        if(extensionPos > 0)
            return filename.substring(0, extensionPos);
        return filename;
}

function isSaveAllowed()
{
    if(checkForEdits()){
        displayStatus("Please complete your edits before you save.");
        return false;
    }

    if(!(Prototype.Browser.Gecko | Prototype.Browser.IE)){
        displayStatus("Save not supported for your browser. Firefox-, Internet Explorer- only.");
        return false;
    }

    return true;
}

function newFile(bNoPrompt)
{
    if(!bNoPrompt)
        if(!confirm("Clear current content? Press Cancel to go back and save current file."))
        return;

    $('DocFilename').innerHTML = 'unnamed.html';
    $('Scrapbook').innerHTML = '';
    $('listBookmarks').innerHTML = '';
    $('DocTitle').innerHTML = 'Untitled Notebook';
    document.title = 'Untitled Notebook';

    CurrentScrap_reset();
    displayStatus('New notebook ready.');
}

function exportView()
{
    createView($('Notebook'));
}

function traverseVisible(target, cursor, depth)
{
    if (cursor.visible()){
        var text = '';
        var i=0;
        var tagName=cursor.tagName;

        if (tagName)
          target.write("<"+tagName+">");

        var cursorChild= cursor.childElements()[i];
        while (cursorChild){
          if(cursorChild.visible()){
              text = Prototype.Browser.IE? cursorChild.innerText:cursorChild.textContent;
              if(!text.blank())
                  target.write(text);
              traverseVisible(target, cursorChild, depth+1);
          }
          i++;
          cursorChild=cursor.childElements()[i];
        }

        if (tagName)
          target.writeln("</"+tagName+">");
    }
}

function createExport(elmt)
{
    var target = window.open();
    target.title = 'Memonaut - Exported View';
    target.document.open();
    target.document.write('<html><head><title>Memonaut - Exported View</title>'
        + '<link rel="stylesheet" type="text/css" href="' + gsAppDir + 'snapshot.css"'
        + '<script type="text/javascript" src="' + gsAppDir + 'prototype.js"> </script>'
        + '<script type="text/javascript" src="' + gsAppDir + 'snapshot.js"> </script>'
        + '</head><body><div id="Notebook">');
    target.document.write(elmt.innerHTML);
    target.document.write("</div></body></html>");
    target.document.close();
}

function restoreArea(elmt){
    var target = elmt.up('.area').down('.areacontent');
    var originalHeight = null;

    if(target){
        if(target.visible()) {
            target.hide();
            originalHeight = target.up('.area').getStyle('height');
            target.up(0).setAttribute('originalheight', originalHeight);
            target.up(0).setStyle({height:'2em'});

        }
        else {
            originalHeight = target.up('.area').getAttribute('originalheight');
            target.up(0).setStyle({height:originalHeight});
            target.show();
        }
    }
}

function intelliScroll(elmt){
    var vpDim = document.viewport.getDimensions();
    var vpOff = document.viewport.getScrollOffsets();
    var elmtHeight = elmt.getHeight();
    var elmtOffset = elmt.cumulativeOffset();
    var bScroll = false;
    
    if (elmtOffset.top >= vpOff.top){
        if((elmtOffset.top + elmtHeight) <= (vpOff.top + vpDim.height)){
            return;
        }
    }
    elmt.scrollTo();
}

function Note_export(elmt)
{
   createExport(elmt);
}

function exportNote(evt)
{
    var target = evt.target.up('.wrapper');
    if(target) Note_export(target);
}

function NotebookList_add(filename)
{
    gasNotebooks.unshift(filename);
}

function saveNotebookList()
{
    var content = 'var gasNotebooks = ' + gasNotebooks.toJSON() + ';';
    saveFileInHomeDirectory(gsAppDir +'notebooks.js', content);
}

function NotebookList_clear()
{
    $('listNotebooks').innerHTML='';
}

function Scrap_join(source, target)
{
    var targetText = Scrap_getContent(target);
    var sourceText = Scrap_getContent(source);

    source = source.down('.scrap').down('.content');
    target = target.down('.scrap').down('.content');

    if(source.empty()){
        displayStatus("No content to merge!");
        return 1;
    }

    var mergedText =  targetText + ' ' + sourceText;
    if(Prototype.Browser.IE){
        target.innerText = mergedText;
        source.innerText = '';
        }
    else{
        target.textContent = mergedText;
        source.textContent = '';
    }

    CurrentScrap_setNew(target);
    var sourceCommentList = source.up('.scrap').down('.commentlist');
    var targetCommentList = null;
    target=target.up('.wrapper');

    if(sourceCommentList){
        targetCommentList = Scrap_getCommentList(target);

        var sourceChildren = sourceCommentList.getElementsBySelector('li');
        for(var i=0;i<sourceChildren.length; i++)
            targetCommentList.insert({bottom:sourceChildren[i]});
    }

    source.up('.wrapper').remove();
}

function Scrap_getContent(wrapper)
{
    var target = wrapper.down('.scrap').down('.content');
    var text = Prototype.Browser.IE? target.innerText:target.textContent;
    return text;
}

function Scrap_merge(elmt, moveUp)
{
    var swapitem = elmt.up('.wrapper');
    var swappers = moveUp ? swapitem.previousSiblings(): swapitem.nextSiblings();

    if (swappers.length > 0){
            var swapper = swappers[0];
            if(!Scrap_join(swapitem, swapper))
                displayStatus('Merged note.');
    }
    else displayStatus('No note to merge into.');
}

function mergePreviousScrap(evt)
{
    var elmt = evt.target;
    Scrap_merge(elmt, true);
}

function mergeNextScrap(evt)
{
    var elmt = evt.target;
    Scrap_merge(elmt, false);
}

function toggleHelp()
{
    var target=$('Help');
    if(target)
        target.toggle();
}

function activateMinimized(target){
    target.addClassName('minimized');
    target.immediateDescendants().each(function (elmt)
            {
                    if(elmt.hasClassName('commentlist')){
                                    elmt.hide();
                    }
            });
    var button = document.createElement('img');
    button.setAttribute('src', gsAppDir + 'folded.png');
    button.setAttribute('title', 'Click to expand.');
    button.addClassName('foldindicator');
    button.addClassName('view');
    button.addClassName('icon');
    target.insert({before:button});
    button.observe('click',FoldIndicator_onClick);
}

function Scrap_mergeParent(elmt)
{
    var source = elmt.up('.wrapper');
    var target = source.up('.wrapper');

    if (target){
            if(!Scrap_join(source, target))
                displayStatus('Merged note.');
    }
    else displayStatus('No note to merge into.');

}

function CurrentScrap_mergePrevious()
{
    if(!gxCurrentScrap) return;
    Scrap_merge(gxCurrentScrap, true);
}

function CurrentScrap_mergeNext()
{
    if(!gxCurrentScrap) return;
    Scrap_merge(gxCurrentScrap, false);

}
function CurrentScrap_mergeParent()
{
    if(!gxCurrentScrap) return;
    Scrap_mergeParent(gxCurrentScrap);

}

function mergeParentScrap(evt)
{
    Scrap_mergeParent(evt.target);
}

function Notebook_remove(evt)
{
    var target = evt.target;
    target = target.up(0);
    target.remove();
    NotebookList_refresh();
}

function Notebook_move(elmt, moveUp)
{
    var swapitem = elmt;
    var swappers = moveUp ? swapitem.previousSiblings(): swapitem.nextSiblings();

    if (swappers.length > 0){
            var swapper = swappers[0];
            Notebook_swap(swapitem, swapper);
            gxMenuNotebookList.refresh();
            NotebookList_refresh();
    }
}

function Notebook_swap(swapitem, swapper)
{
    //This is OK only because there are no child elements. Otherwise handlers lost...
    var itemtext = swapper.innerHTML;
    swapper.innerHTML = swapitem.innerHTML;
    swapitem.innerHTML = itemtext;
}

function Notebook_moveUp(evt)
{
    var elmt = evt.target.up(0);
    Notebook_move(elmt, true);
}

function Notebook_moveDown(evt)
{
    var elmt = evt.target.up(0);
    Notebook_move(elmt, false);
}

function NotebookList_refresh()
{
    gasNotebooks = [];

    var displistNotebook = $$('#listNotebooks li a');
    for(var i=0; i< displistNotebook.length; i++){
        var notebook = displistNotebook[i];
        var name = Prototype.Browser.IE? notebook.innerText:  notebook.textContent;
        gasNotebooks.push(name);
    }
}